# -*- coding: utf-8 -*-

#    Copyright (C) 2005-2013 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>
#    This file is part of Promogest.

#    Promogest is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    Promogest is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with Promogest.  If not, see <http://www.gnu.org/licenses/>.


from sqlalchemy import *
from sqlalchemy.orm import *
from lib.alembic.migration import MigrationContext
from lib.alembic.operations import Operations
from lib.alembic import op
from Environment import *
from dao.DaoUtils import get_columns
from web_lib.webutils import leggiInSessione

try:
    t_static_page=Table('static_page',
        meta,
        schema = leggiInSessione(sezione="Main", chiave="schema"),
        autoload=True)
except:
    from data.staticPages import t_static_page


from dao.StaticPagesCategory import StaticPagesCategory, t_static_pages_category

colonne_categoria = get_columns(t_static_page)
if "id_categoria" not in colonne_categoria:
    conn = engine.connect()
    ctx = MigrationContext.configure(conn)
    op = Operations(ctx)
    op.add_column('static_page', Column('id_categoria', Integer,ForeignKey(fk_prefix_main+'static_pages_category.id')),schema=leggiInSessione(sezione="Main", chiave="schema"))


from dao.Dao import Dao
from dao.Language import Language, t_language



class StaticPages(Dao):

    def __init__(self, req=None):
        Dao.__init__(self, entity=self)

    @property
    def tipo_static_pages(self):
        if self.id_categoria:
            a = StaticPagesCategory().getRecord(id=self.id_categoria)
            if a:
                return a.denominazione
            else:
                return None
        else:
            return None


    def filter_values(self,k,v):
        if k=='id_categoria':
            dic= {  k : t_static_page.c.id_categoria == v}
        elif k == "titlePage":
            dic = { k: t_static_page.c.title==v }
        elif k == "permalink":
            dic = { k: t_static_page.c.permalink==v }
        return  dic[k]


std_mapper = mapper(StaticPages, t_static_page,
        properties = {
            #'lang' : relation(Language,
                        #primaryjoin= t_static_page.c.id_language==t_language.c.id,
                        #foreign_keys=[t_language.c.id]),
            #'categoria_sp':relation(StaticPagesCategory, backref='staticpages'),
        },
        order_by=t_static_page.c.id)
